package cn.fws.meap.weiChatWeb;

import cn.fws.framework.utils.UUIDUtils;
import cn.fws.framework.web.contoller.BaseController;
import cn.fws.framework.web.contoller.JsonResponse;
import cn.fws.meap.community.enums.BountyEnum;
import cn.fws.meap.system.vo.OrderInfo;
import cn.fws.meap.system.vo.OrderReturnInfo;
import cn.fws.meap.system.constants.WeChat;
import cn.fws.meap.user.entity.User;
import cn.fws.meap.user.service.IUserService;
import cn.fws.meap.utils.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

import static cn.fws.meap.utils.HttpUtil.formatUrlMap;

@RestController
@RequestMapping("/meap/pay")
@Api(tags = "统一下单")
public class WeChatPayController extends BaseController {


    @Autowired
    private IUserService userService;

    @Value("${serverIP}")
    private String notify_url;//回调ip
    @Value("${serverIP}")
    private String spbill_create_ip;//服务ip

    @ApiOperation(value = "微信小程序支付")
    @PostMapping("/payment")
    public JsonResponse pay(String openId,Integer total_fee) throws IllegalAccessException {


        User user = userService.selectById(openId);
        user.getOpenid();
        OrderInfo orderInfo=new OrderInfo();
        orderInfo.setAppid(WeChat.APPID);
        orderInfo.setBody(BountyEnum.PROBLEM_BOUNTY.getName());//问题赏金
        orderInfo.setMch_id(WeChat.MCH_ID);
        orderInfo.setNonce_str(UUIDUtils.getUUID());
        orderInfo.setOut_trade_no(UUIDUtils.getUUID());
        orderInfo.setOpenid(user.getOpenid());
        orderInfo.setTotal_fee(total_fee);
        orderInfo.setSpbill_create_ip(spbill_create_ip);
        orderInfo.setTrade_type("JSAPI");
        orderInfo.setNotify_url("http://"+notify_url+":6001/fws-meap-service/meap/pay/notifyWeiXinPay");
        System.out.println("回调地址-----"+orderInfo.getNotify_url());
        Map<String, String> map = new HashMap<>();
        map.put("appid", orderInfo.getAppid()); //小程序appid
        map.put("body", orderInfo.getBody()); //商品描述
        map.put("mch_id", orderInfo.getMch_id()); //商户号
        map.put("nonce_str", orderInfo.getNonce_str()); //32位随机码
        map.put("out_trade_no", orderInfo.getOut_trade_no()); //订单号
        map.put("openid", orderInfo.getOpenid()); //小程序用户openid
        map.put("total_fee", String.valueOf(orderInfo.getTotal_fee()));//费用
        map.put("spbill_create_ip", orderInfo.getSpbill_create_ip()); //ip地址
        map.put("notify_url", orderInfo.getNotify_url());//回调URL
        map.put("trade_type", orderInfo.getTrade_type()); //支付方式

        //使用ASKII码进行排序
        String stringA = formatUrlMap(map, false, false);

        //加上+key，并转换成大写
        String sign = MD5Until.md5Encrypt32Upper(stringA + "&key="+WeChat.PaySignKey).toUpperCase();

        String xml = "<xml>" + "<appid>"
                + orderInfo.getAppid() + "</appid>"
                + "<body>" + orderInfo.getBody()+ "</body>"
                + "<mch_id>" + orderInfo.getMch_id() + "</mch_id>"
                + "<nonce_str>" + orderInfo.getNonce_str() + "</nonce_str>"
                + "<notify_url>" + orderInfo.getNotify_url() + "</notify_url>"
                + "<openid>" + orderInfo.getOpenid() + "</openid>"
                + "<out_trade_no>" +  orderInfo.getOut_trade_no() + "</out_trade_no>"
                + "<spbill_create_ip>" + orderInfo.getSpbill_create_ip() + "</spbill_create_ip>"
                + "<total_fee>" + String.valueOf(orderInfo.getTotal_fee())+ "</total_fee>"
                + "<trade_type>"+ orderInfo.getTrade_type()+"</trade_type>"
                + "<sign>" + sign + "</sign>"
                + "</xml>";

        //获得返回结果
        String result = WechatUtils.httpRequest(WeChat.PAY_URL,"POST",xml);
        System.out.println("统一下单返回的结果+++++++"+result);


       // xml转对象
        OrderReturnInfo orderReturnInof = XmlUtil.converyToJavaBean(result, OrderReturnInfo.class);

        if ("SUCCESS".equals(orderReturnInof.getReturn_code()) && orderReturnInof.getReturn_code().equals(orderReturnInof.getResult_code())) {
            System.out.println("下单成功返回的对象，下面");


            long time = System.currentTimeMillis()/1000;

            Map payInfo = new HashMap();
            payInfo.put("appId",WeChat.APPID);
            payInfo.put("timeStamp", String.valueOf(time));
            payInfo.put("nonceStr", UUIDUtils.getUUID());
            payInfo.put("package", "prepay_id="+orderReturnInof.getPrepay_id());
            payInfo.put("signType", "MD5");

            String sign1 = Signature.getSign(payInfo);
            System.out.println("第二次签名------0------"+sign1);
            payInfo.put("paySign", sign1);
            payInfo.put("order",orderInfo.getOut_trade_no());
            payInfo.put("status", 200);
            payInfo.put("msg", "统一下单成功!");

            // 此处可以写唤起支付前的业务逻辑

            // 业务逻辑结束
            return JsonResponse.success("操作成功",payInfo);

        }else {

            return JsonResponse.error("下单失败");
        }

    }
    @RequestMapping(value = "notifyWeiXinPay", produces = MediaType.APPLICATION_JSON_VALUE)
    public String notifyWeiXinPay(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("微信支付回调");
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        String resultxml = new String(outSteam.toByteArray(), "utf-8");
        System.out.println(resultxml);
        outSteam.close();
        inStream.close();

        String s="<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
        return s;
    }

    /**
     * 此函数会被执行多次，如果支付状态已经修改为已支付，则下次再调的时候判断是否已经支付，如果已经支付了，则什么也执行
     * @param request
     * @param response
     * @return
     * @throws IOException
     * @throws JDOMException
     */
    /*@RequestMapping(value = "notifyWeiXinPay", produces = MediaType.APPLICATION_JSON_VALUE)
    // @RequestDescription("支付回调地址")
    @ResponseBody
    public String notifyWeiXinPay(HttpServletRequest request, HttpServletResponse response) throws IOException, JDOMException {
        System.out.println("微信支付回调");
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        String resultxml = new String(outSteam.toByteArray(), "utf-8");
        Map<String, String> params = PayCommonUtil.doXMLParse(resultxml);
        outSteam.close();
        inStream.close();


        Map<String,String> return_data = new HashMap<String,String>();
        if (!PayCommonUtil.isTenpaySign(params)) {
            // 支付失败
            return_data.put("return_code", "FAIL");
            return_data.put("return_msg", "return_code不正确");
            return StringUtil.GetMapToXML(return_data);
        } else {
            System.out.println("===============付款成功==============");
            // ------------------------------
            // 处理业务开始
            // ------------------------------
            // 此处处理订单状态，结合自己的订单数据完成订单状态的更新
            // ------------------------------

            String total_fee = params.get("total_fee");
            double v = Double.valueOf(total_fee) / 100;
            String out_trade_no = String.valueOf(Long.parseLong(params.get("out_trade_no").split("O")[0]));
            Date accountTime = DateUtil.stringtoDate(params.get("time_end"), "yyyyMMddHHmmss");
            String ordertime = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
            String totalAmount = String.valueOf(v);
            String appId = params.get("appid");
            String tradeNo = params.get("transaction_id");

            return_data.put("return_code", "SUCCESS");
            return_data.put("return_msg", "OK");
            return StringUtil.GetMapToXML(return_data);
        }
    }*/




}

